import React, { useState, useEffect, useCallback, } from 'react'
import { Col, Form, Input, Button, Table, Modal, Checkbox, InputNumber, Switch, message, Row, Select, Popconfirm, } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import ModalGroup from './components/modalContent'
import {
  fetchSchemeLists,
  addScheme,
  setAllGoods,
} from '@/services/distribution/setting'
import { formItemLayout } from '@/utils/utils'
import { connect } from 'dva'
import { router } from 'umi'

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const col = [
  {
    title: '分销方案id',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '分销方案名称',
    dataIndex: 'distributionName',
    key: 'distributionName',
  },
  {
    title: '详情记录',
    dataIndex: 'version',
    key: 'version',
  },
  {
    title: '创建时间',
    dataIndex: 'cardCommissionValue',
    key: 'cardCommissionValue',
  },
  {
    title: '开启/关闭时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: (t) => <>{t == 0 ? '开启' : '关闭'}</>
  },
]
const Scheme = props => {
  const { form, distribute, btns, } = props
  const { inform } = distribute
  const { getFieldDecorator } = form
  const [data, setData] = useState([])
  const [record, setRecord] = useState([])
  const [visible, setVisible] = useState(false)
  const [isShow, setModal] = useState(false)
  const [isCheck, setCheck] = useState(false)
  const [type, setType] = useState('0')

  useEffect(() => {
    init()
  }, [])

  const init = async (params = '/1/10') => {
    const res = await fetchSchemeLists(params)
    setData(res.data)
  }

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)

    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return (
      <>
        <Col span={6}>
          <Form.Item label={`方案名称`}>
            {getFieldDecorator(`condition[distributionName]`, {})
              (<Input />)}
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item label={`方案状态`}>
            {getFieldDecorator(`condition[status]`, {})
              (<Input />)}
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item label={`分销对象`}>
            {getFieldDecorator(`condition[roleType]`, {})
              (<Input />)}
          </Form.Item>
        </Col>
      </>
    )
  }

  // 新增/修改模态框
  const handleStatus = useCallback(record => {
    setVisible(!visible);
    props.dispatch({
      type: 'distribute/saveData',
      payload: {
        inform: record,
      },
    });
  }, [visible]);

  // 按钮处理
  const handleBtn = type => {
    console.log(type)
    if (record.length == 0 && ![1].includes(type)) return message.warning('请选择一条数据')
    switch (type) {
      case 1: // add
        return handleStatus()
      case 3: //edit
        return handleStatus(record[0])
      case 81:
        return router.push('/distribution/setting/single')
      case 82:
        return 
      default:
        break;
    }
  }

  const editData = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      editMembershipCards({
        employeeCashRegisterSetting: {
          ...record[0],
          ...values,
          cardStatus: values.cardStatus ? '1' : '0',
        }
      }).then(res => {
        if (res.code == 0) {
          setVisible(!visible)
          init()
        } else {
          message.warning(res.msg)   
        }
      })
    })
  }
  const settingTypes = () => {

  }

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
  };

  const confirm = async () => {
    if (record.length == 0) return message.warning('请选择一条数据')
    const res = await setAllGoods({
      coverSettings: false,
      distributionId: record[0].id
    })
    message.info(res.msg)
  }

  const cancel = () => {

  }
  
  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom 
        click={handleBtn} 
        filterTypes={[2, 80,]} 
      />
      {
        btns.length > 0 && btns.filter(b => b.type == 80).map(el => (
          <Popconfirm
            title="是否覆盖所有商品的原有设置?"
            onConfirm={confirm}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button key={el.id} type="primary" >{el.name}</Button>
          </Popconfirm>
        ))
      }
      <Table 
        columns={col}
        dataSource={data}
        rowSelection={rowSelection}
        rowKey={r => r.id}
      />
      <Modal
        title='分类设置'
        visible={isShow}
        onOk={settingTypes}
        onCancel={() => setModal(!isShow)}
      >
        <Select>

        </Select>
      </Modal>
      <Modal
        title='新增/编辑'
        visible={visible}
        onOk={editData}
        onCancel={() => setVisible(!visible)}
      >
        <Form {...formItemLayout}>
          <Form.Item label="方案名称">
            {getFieldDecorator('cardStatus', {
              initialValue: inform && inform.cardStatus,
              valuePropName: 'checked',
            })(<Input />)}
          </Form.Item>
          {/* <ModalGroup /> */}
          <Form.Item label="角色对象">
            {getFieldDecorator('cardStatus', {
              initialValue: inform && inform.cardStatus,
              valuePropName: 'checked',
            })(<Checkbox.Group>
                <Checkbox value={1}>员工</Checkbox>
                <Checkbox value={2}>会员</Checkbox>
                <Checkbox value={3}>渠道商</Checkbox>
              </Checkbox.Group>)}
          </Form.Item>
          <Form.Item label="提成方式">
            {getFieldDecorator('cardStatus', {
              initialValue: inform && inform.cardStatus,
              valuePropName: 'checked',
            })(
              <Row>
                <Col span={10}>
                  <Select defaultValue="0" onChange={val => setType(val)}>
                    <Select.Option value={'0'}>比例</Select.Option>
                    <Select.Option value={'1'}>定额</Select.Option>
                  </Select>
                </Col>
                <Col span={10}><Input addonAfter={type == 0 ? '%' : '元'} /></Col>
              </Row>
            )}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
    )
}

export default connect(({distribute, global}) => ({
  distribute,
  btns: global.btns,
}))(Form.create()(Scheme))
